<template>
  <div class="app-container">
    <!-- @click="handleAddNotice"   -->
    <el-button type="primary" @click="openDialog">创建新公告</el-button>

    <el-table v-loading="listLoading" :data="noticePage.data" style="width: 100%;margin-top:20px;" border>
      <el-table-column :resizable="false" align="center" label="序号" width="80">
        <template slot-scope="{scope, $index}">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :resizable="false" align="center" label="公告标题" width="350">
        <template slot-scope="scope">
          {{ scope.row.noticeTitle }}
        </template>
      </el-table-column>
      <el-table-column align="center" :resizable="false" label="创建人" width="250">
        <template slot-scope="scope">
          {{ scope.row.user.nickName }}
        </template>
      </el-table-column>
      <el-table-column :resizable="false" align="center" label="是否推送" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isPush"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ccc"
            @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" :resizable="false" label="创建时间" width="250">
        <template slot-scope="scope">
          {{ scope.row.publishTime }}
        </template>
      </el-table-column>

      <el-table-column align="center" :resizable="false" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleDetail(scope)">详情</el-button>
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="detailVisible" :title="currentNotice.noticeTitle" width="60%">
      <div>
        <v-md-editor :value="currentNotice.noticeContent" mode="preview" />
      </div>
    </el-dialog>

    <el-dialog
      title="编辑公告"
      :visible.sync="dialogVisible"
      width="60%"
      center
      @close="resetForm"
    >
      <el-form ref="ruleForm" :model="noticeInfo" status-icon :rules="rules" class="content-all">
        <el-form-item label-width="50px" label="标题" prop="noticeTitle">
          <el-input v-model="noticeInfo.noticeTitle" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label-width="50px" label="推送">
          <el-switch
            v-model="noticeInfo.isPush"
            active-color="#13ce66"
            inactive-color="#ccc"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label-width="1px" prop="noticeContent">
          <v-md-editor
            v-model="noticeInfo.noticeContent"
            height="400px"
            :disabled-menus="[]"
            @upload-image="handleUploadImage"
          />
        </el-form-item>
        <el-form-item class="el-form-submit">
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { deleteNotice, getNoticeList, saveOrUpdateNotice, getNoticeInfo, updatePushStatus } from '@/api/notice'
import { deepClone } from '@/utils'
import { URL_PREFIX } from '@/api/config'
import { fileUpload } from '@/api/base'

export default {
  name: 'Notice',
  data() {
    return {
      dialogVisible: false,
      listLoading: false,
      noticePage: {},
      noticeList: [],
      pageQuery: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        isPush: null
      },
      currentNotice: {},
      detailVisible: false,
      detailContent: '',
      noticeInfo: {
        id: null,
        noticeTitle: '',
        noticeContent: '',
        isPush: null
      },
      rules: {
        noticeTitle: [
          { message: '公告标题为必传项', required: true, trigger: 'blur' }
        ],
        noticeContent: [
          { message: '公告内容为必传项', required: true, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 点击页面组件的时候，执行方法
    this.getList()
  },
  methods: {
    // 更新推送的状态
    handleSwitchChange(row) {
      console.log('handleSwitchChange----', row.id, row.isPush)
      // 执行推送更新操作
      updatePushStatus(row.id, row.isPush)
        .then(() => {
          this.$message.success('推送状态更新成功')
        })
        .catch(() => {
          this.$message.error('推送状态更新失败')
        })
    },
    getList() {
      this.listLoading = true
      getNoticeList(this.pageQuery).then(res => {
        this.listLoading = false
        this.noticePage = res.data
      })
    },
    handleDetail(scope) {
      this.currentNotice = deepClone(scope.row)
      this.detailVisible = true
    },
    handleEdit(scope) {
      const id = scope.row.id
      getNoticeInfo(id).then(response => {
        console.log('response.data----', response.data)
        this.noticeInfo = response.data
        this.dialogVisible = true
      }).catch(error => {
        console.error('点击编辑获取数据失败：', error)
        this.$message.error('获取数据失败')
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确定要删除这个公告吗?', '删除公告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteNotice(row.id)
          this.$message({
            type: 'success',
            message: '公告删除成功!'
          })
          this.getList()
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 创建公告，弹窗窗口
    openDialog() {
      // 控制对话框的显示和隐藏
      this.dialogVisible = true
    },
    resetForm() {
      // 重置表单字段
      this.$refs['ruleForm'].resetFields()
    },
    handleUploadImage(event, insertImage, files) {
      fileUpload(files[0]).then(res => {
        insertImage({
          url: URL_PREFIX + res.data,
          desc: '描述',
          width: 'auto',
          height: 'auto'
        })
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveOrUpdateNotice(this.noticeInfo).then(res => {
            this.$message.success('公告操作成功')
            this.resetForm()
            this.dialogVisible = false
            // 点击提交，关闭弹窗，局部刷新页面
            this.getList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content-all {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
}
.el-form-submit{
  margin-bottom: -5px;
}
</style>
